<script setup> 
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryPageApi, addUserApi, queryInfoApi, updateUserApi, deleteUserApi, queryInfoByAccountApi } from '@/api/user'
//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])
//状态列表数据
const states = ref([{ name: '正常', value: 1 }, { name: '禁用', value: 0 }])
//部门列表数据
const userList = ref([])

const searchUser = ref({
  nickname: '',
  gender: '',
  state: '', 
  date: [],
  begin: '',
  end: ''
})
//侦听date属性
watch(
  () => searchUser.value.date,
  (newValue, oldValue) => {
     if(newValue.length == 2){
      searchUser.value.begin = newValue[0]
      searchUser.value.end = newValue[1]
     }else {
      searchUser.value.begin = ''
      searchUser.value.end = ''
     }
  }
)
//声明token
const token = ref('')

onMounted(async () => {
  handleSearch()

  //加载localStorage存储的用户登录信息
  const loginUser =  localStorage.getItem('loginUser');
  if(loginUser){
    token.value = JSON.parse(loginUser).token
  }
})

//查询用户
const handleSearch = async () => {
  console.log('Search:', searchUser.value)
  const result = await queryPageApi(searchUser.value.nickname, searchUser.value.gender, searchUser.value.state, searchUser.value.begin, searchUser.value.end, currentPage.value, pageSize.value);
  if(result.code){
    userList.value = result.data.records
    total.value = result.data.total
  }
}
const handleReset = () => {
  // 清空表单
  searchUser.value = {
    nickname: '',
    gender: '',
    state: '', 
    date: [],
    begin: '',
    end: ''
  }
  handleSearch()
}


// 分页配置
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}
// 操作处理
const handleEdit = async (id) => {
  console.log('Edit:', id)
  const result = await queryInfoApi(id);
  if(result.code){
    dialogVisible.value = true
    dialogTitle.value = '修改用户'
    user.value = result.data
  }
  
  userFormRef.value.resetFields()
}
// 删除单个用户
const handleDelete = async (id) => {
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除该用户吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除用户
    const result = await deleteUserApi(id);
    if(result.code){
      ElMessage.success('删除用户成功') 
      handleSearch()
    }else{
      ElMessage.error(result.msg)
    }
  })
}

//新增用户
const addUser = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增用户'
  user.value = {
    nickname: '',
    gender: '1',
    createTime: '',
    avatar: '',
    account: '',
    password: '',
    state: '1',
  }
  userFormRef.value.resetFields()
}

//新增/修改表单
const userFormRef = ref(null)
const user = ref({
  nickname: '',
    gender: '',
    createTime: '',
    avatar: '',
    account: '',
    password: '',
    state: '',
})  

//表单校验规则
// 验证规则
const rules = ref({
  state: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  account: {
    validator: async (rule, value, callback) => {
      // 只有在新增用户时才进行账号验证
      if (!user.value.id) {
        if (!value) {
          callback(new Error('请输入账号'));
        } else if (value.length < 2 || value.length > 20) {
          callback(new Error('账号长度应在2到20个字符之间'));
        } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
          callback(new Error('账号只能包含字母、数字和下划线'));
        } else {
          const res = await queryInfoByAccountApi(value);
          if (res.code) {
            callback(new Error('账号已存在'));
          } else {
            callback();
          }
        }
      } else {
        // 编辑模式下直接通过验证
        callback();
      }
    },
    trigger: 'blur'
  }
});

// 控制弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')

// 图片上传成功后触发
const handleAvatarSuccess = (response,uploadFile) => {
  ElMessage.success('图片上传成功')
  user.value.avatar = response.data
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}
//保存用户信息
const save = async () => {
  userFormRef.value.validate(async valid => {
    if(valid){ // 校验通过
      let result ;
      if(user.value.id){ //存在ID, 修改
        result = await updateUserApi(user.value);
      }else { //不存在ID, 新增
        result = await addUserApi(user.value);
      }
      if(result.code){
        ElMessage.success('保存用户成功')
        dialogVisible.value = false
        handleSearch()
      }else {
        ElMessage.error(result.msg)
      }
    }
  })
}

// 存储选中的 ID
const selectedIds = ref([]);

// 处理复选框选择变化的函数
function handleSelectionChange(selection) {
  const ids = selection.map(item => item.id);
  selectedIds.value = ids;
}

//批量删除用户
const deleteByIds = async () => {
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除选中用户吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除用户
    const result = await deleteUserApi(selectedIds.value);
    if(result.code){
      ElMessage.success('删除用户成功')
      handleSearch()
    }else{
      ElMessage.error(result.msg)
    }
  })
}
</script>
<template> 
<h1>用户管理</h1> <br>
  <el-form :inline="true" :model="searchUser">
    <el-form-item label="姓名">
      <el-input v-model="searchUser.nickname" placeholder="请输入用户姓名"></el-input>
    </el-form-item>

    <el-form-item label="性别">
      <el-select v-model="searchUser.gender" placeholder="请选择">
        <el-option label="男" value="1"></el-option>
        <el-option label="女" value="2"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="状态">
      <el-select v-model="searchUser.state" placeholder="请选择">
        <el-option label="正常" value="1"></el-option>
        <el-option label="禁用" value="0"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="加入日期">
      <el-date-picker
        v-model="searchUser.date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
      ></el-date-picker>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>


  <el-button type="primary" @click="addUser"> + 新增用户</el-button>
  <el-button type="danger" @click="deleteByIds"> - 批量删除</el-button>
  <br><br>

  <!-- 表格 -->
  <el-table :data="userList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="50" align="center"></el-table-column>
    <el-table-column prop="nickname" label="姓名" width="100" align="center"></el-table-column>
    <el-table-column label="性别" width="80" align="center">
      <template #default="scope" >
        {{ scope.row.gender == 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column label="头像" width="100" align="center">
      <template #default="scope" >
        <img :src="scope.row.avatar" alt="Avatar" class="avatar" />
      </template>
    </el-table-column>
    <el-table-column prop="account" label="账号" width="100" align="center"></el-table-column>
    <el-table-column label="状态" width="80" align="center">
      <template #default="scope" >
        {{ scope.row.state == 1 ? '正常' : '禁用' }}
      </template>
    </el-table-column>
    <el-table-column prop="birthday" label="生日" width="100" align="center"></el-table-column>
    <el-table-column prop="createTime" label="加入日期" width="100" align="center"></el-table-column>
    <el-table-column prop="updateTime" label="最后操作时间" width="100" align="center"></el-table-column>
    <el-table-column label="操作" fixed="right" align="center">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>

  <!-- 分页 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[10, 20, 30, 40]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
  >
  </el-pagination>

  <!-- 新增/修改用户的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form ref="userFormRef" :model="user" :rules="rules" label-width="80px">
        <!-- 基本信息 -->
         <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账号" prop="account">
              <el-input v-model="user.account" placeholder="请输入账号，2-20个字" :disabled="user.id !== undefined && user.id !== null"></el-input>
            </el-form-item>
          </el-col>
        <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="user.password" placeholder="请输入密码，6-20个字"></el-input>
            </el-form-item>
          </el-col>  
        </el-row>
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="nickname">
              <el-input v-model="user.nickname" placeholder="请输入用户名，2-20个字"></el-input>
            </el-form-item>
          </el-col>
        <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="user.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option v-for="gender in genders" :key="gender.name" :label="gender.name" :value="gender.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>  
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                v-model="user.birthday"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择生日"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-select v-model="user.state" placeholder="请选择状态" style="width: 100%;">
                <el-option v-for="state in states" :key="state.name" :label="state.name" :value="state.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>  
        </el-row>
       
        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :headers="{'token': token}"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                >
                <img v-if="user.avatar" :src="user.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
  </el-dialog>

</template>
<style scoped> 
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>